﻿/*
Copyright © 2011 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Collections.Generic;

namespace Simple.Storage.Api
{
    /// <summary>
    /// Implements a simple cache used to avoid cycle during saving.
    /// </summary>
    internal class SavingCache
    {
        /// <summary>
        /// The saved data.
        /// </summary>
        private readonly IDictionary<Type, ICollection<object>> cache
            = new Dictionary<Type, ICollection<object>>();

        /// <summary>
        /// Checks if a specific object is already saved.
        /// </summary>
        /// <param name="type">The type of the object.</param>
        /// <param name="key">The key of the object.</param>
        /// <returns>
        /// <c>true</c> if the object associated with <paramref name="key"/> is already saved;
        /// <c>false</c> otherwise.
        /// </returns>
        public bool IsSaved(Type type, object key)
        {
            return type != null
                && this.cache.ContainsKey(type)
                && this.cache[type].Contains(key);
        }

        /// <summary>
        /// Registers an object as saved.
        /// </summary>
        /// <param name="type">The type of the object.</param>
        /// <param name="key">The key of the object.</param>
        public void Saved(Type type, object key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (!this.cache.ContainsKey(type))
            {
                this.cache.Add(type, new List<object>());
            }

            if (!this.cache[type].Contains(key))
            {
                this.cache[type].Add(key);
            }
        }

        /// <summary>
        /// Clears the cache.
        /// </summary>
        public void Clear()
        {
            this.cache.Clear();
        }
    }
}
